package com.cwits.wifi.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.cwits.wifi.MainApplication;
import com.cwits.wifi.R;
import com.cwits.wifi.base.baseinterface.IBaseActivity;
import com.cwits.wifi.manager.ControlManager;
import com.cwits.wifi.tool.ActivityStack;
import com.cwits.wifi.tool.WifiHelper;
import com.cwits.wifi.ui.dialog.DeviceListDialog;
import com.cwits.wifi.ui.dialog.InputPasswordDialog;
import com.cwits.wifi.ui.dialog.NotifyDialog;
import com.cwits.wifi.ui.service.CommunicationService;
import com.cwits.wifi.ui.view.WaitDialog;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.Dbug;
import com.cwits.wifi.util.IAction;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.PreferencesHelper;
import com.jieli.lib.stream.beans.StateInfo;
import com.jieli.lib.stream.tools.CommandHub;
import com.jieli.lib.stream.tools.ParseHelper;
import com.jieli.lib.stream.util.ICommon;

import java.io.File;
import java.util.List;
import java.util.Locale;

/**
 * Created by ZhangHua on 2016-02-26.
 */
public class BaseActivity2 extends FragmentActivity implements IBaseActivity, OnItemClickListener, ICommon, IAction, IConstant, CommunicationService.OnUsbModeListener {
    private final String tag = getClass().getSimpleName();
    private AlertView mAlertView;
    private Toast mToastShort, mToastLong;
    public MainApplication mApplication;
    private NotifyDialog mConnectionErrorNotify;
    private NotifyDialog mUsbModeDialog;
    private NotifyDialog mNotifyDialog, mPasswordErrorDialog;
    private static boolean isReadyToConnect = false;
    private static boolean isNeedReconnection = false;
    private boolean isBrowsing = false;
    private WifiHelper mWifiHelper;
    public static String mConnectingSSID;
    public static String mPassWord;

    private Handler mWaiteHandler;
    protected boolean isTimeOut = false;//是否超时
    protected boolean isDeal = false;//是否已处理，即有收到第一个包。
    private WaitDialog mProgressDialog;

    //对于设备wifi状态监听
    public static int DEVICE_WIFI_ENABLED = 1;
    public static int DEVICE_WIFI_DISABLED = 2;
    public static int DEVICE_WIFI_CONNECTING = 3;
    public static int DEVICE_WIFI_CONNECTED = 4;
    NotifyDialog mSearchWiFiDialog;

    public static final int ERROR = 10001;
    public static final int COOKIE_INVILD = 10002;
    private boolean mIsAutoDisabled_Device_WIFI = false;
    private SystemBarTintManager mSystemBarTintManager;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTION_DEVICE_WIFI_DISABLED:
                    mAlertView = new AlertView(getString(R.string.dialog_tip), getString(R.string.device_is_disabled_wifi), null, new String[]{getString(R.string.confirm)},
                            null, context, AlertView.Style.Alert, BaseActivity2.this);
                    mAlertView.setCancelable(false);
                    mAlertView.show();
                    mApplication.setErrorFlag(true);
                    if (mApplication.getIsOffLineMode() == false) {
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                        onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    }

                    break;
                case ACTION_SDCARD_STATE:
                    StateInfo stateInfo = (StateInfo) intent.getSerializableExtra(KEY_SDCARD_STATE);
                    onMountState(stateInfo.getParam()[0], stateInfo.getParam()[0]);
                    break;
                case ACTION_DEVICE_CONNECTION_ERROR:

                    int errorType = intent.getIntExtra(KEY_DEVICE_CONNECTION_ERROR, -1);

                    Dbug.i(tag, "==errorType==" + errorType);
                    switch (errorType) {
                        case CommandHub.ERROR_CONNECTION_EXCEPTION:
                            mConnectionErrorNotify.setContent(R.string.connect_failed);
                            mApplication.setErrorFlag(true);
                            break;
                        case CommandHub.ERROR_CONNECTION_TIMEOUT:
                            mConnectionErrorNotify.setContent(R.string.connection_timeout);
                            mApplication.setErrorFlag(true);
                            break;
                    }
                    if (mApplication.getIsOffLineMode() == false) {
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                        onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    }
                    if (mConnectionErrorNotify != null && mConnectionErrorNotify.isShowing()) {
                        mConnectionErrorNotify.dismiss();
                    }
                    if (mConnectionErrorNotify != null) {
                        if (mConnectionErrorNotify != null && mConnectionErrorNotify.isAdded() && !mConnectionErrorNotify.isShowing()) {
                            mConnectionErrorNotify.show(getFragmentManager(), "ConnectionErrorNotify");
                        }
                    }
                    break;
                case ACTION_REJECT_CONNECTION:
                    if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                        mNotifyDialog.dismiss();
                    }
                    new AlertView(getString(R.string.dialog_tip), getString(R.string.reject_connection),
                            null, new String[]{getString(R.string.exit)},
                            null, BaseActivity2.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int i) {
                            exit();
                        }
                    }).setCancelable(false).show();
                    if (mApplication.getIsOffLineMode() == false) {
                        mApplication.setIsOffLineMode(true);
                        mApplication.setRealCamera(false);
                        onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                    }
                    break;
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    if (wifiInfo == null || TextUtils.isEmpty(wifiInfo.getSSID())) {
                        Dbug.e(tag, "SSID is null");
                        //connectDevice();
                        if (mApplication.getIsOffLineMode() == false) {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                        }
                        connectError();
                        return;
                    }
                    final String prefixSSID = wifiInfo.getSSID().replace("\"", "");
                    Dbug.i(tag, "Current prefixSSID=====" + prefixSSID + ", getNetworkId==" + wifiInfo.getNetworkId());

                    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    Dbug.e(tag, "Is connected: " + info.isConnected() + ", isNeedReconnection=" + isNeedReconnection + ",isReadyToConnect=" + isReadyToConnect);
                    if (info.isConnected() && wifiInfo.getNetworkId() >= 0 && (prefixSSID.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID.contains(WIFI_PREFIX_168)) && isReadyToConnect) {

                        if (isNeedReconnection) {
                            isNeedReconnection = false;
                        }
                        Dbug.e(tag, "Connect device wifi success, now init=====");
//                        init();
                        //sendCommandToService(IConstant.SERVICE_CMD_INIT_SOCKET);
                        initSocket();
                        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                            mNotifyDialog.dismiss();
                        }
                        isReadyToConnect = false;
                    } else if (info.isConnected() == false || (prefixSSID != null && (prefixSSID.startsWith(WIFI_PREFIX_CAMERA) == false&&prefixSSID.startsWith(WIFI_PREFIX_CARDVR) == false)&&prefixSSID.contains(WIFI_PREFIX_168) == false)) {
                        //if(isReadyToConnect)
                        //onWiFiState(mIsAutoDisabled_Device_WIFI,DEVICE_WIFI_DISABLED);
                    } else {

                    }
                    break;
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    WifiManager wifiManager1 = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo11 = wifiManager1.getConnectionInfo();
                    String prefixSSID1 = "";
                    if (wifiInfo11 != null)
                        prefixSSID1 = wifiInfo11.getSSID().replace("\"", "");
                    NetworkInfo wifiInfo1 = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                    if (wifiInfo1 != null && wifiInfo11 != null && (prefixSSID1.startsWith(WIFI_PREFIX_CAMERA)||prefixSSID1.startsWith(WIFI_PREFIX_CARDVR)||prefixSSID1.contains(WIFI_PREFIX_168)) && TextUtils.isEmpty(wifiInfo11.getSSID()) == false) {
                        //do nothing
                    } else {
                        if (mApplication.getIsOffLineMode() == false) {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                        }
                    }
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
                    int supplicantError = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -1);
//                    Dbug.d(tag, "supplicantError=" + supplicantError + ", state=" + state);
                    if (SupplicantState.DISCONNECTED.equals(state) && supplicantError == WifiManager.ERROR_AUTHENTICATING && isReadyToConnect) {

                        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                            mNotifyDialog.dismiss();
                        }
                        isReadyToConnect = false;
                        if (mApplication.getIsOffLineMode() == false) {
                            mApplication.setIsOffLineMode(true);
                            mApplication.setRealCamera(false);
                            onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_DISABLED);
                        }
                        PreferencesHelper.remove(MainApplication.getApplication(), mConnectingSSID);

                        if (mPasswordErrorDialog == null) {
                            mPasswordErrorDialog = new NotifyDialog(R.string.dialog_tip, R.string.pwd_incorrect, R.string.confirm, new NotifyDialog.OnConfirmClickListener() {
                                @Override
                                public void onClick() {
                                    mPasswordErrorDialog.dismiss();

                                    removeCurrentNetwork();

                                    searchDevice();
                                }
                            });
                        }
                        mPasswordErrorDialog.show(getFragmentManager(), "mPasswordErrorDialog");
                    }
                    break;
                case ACTION_REQUEST_UI_DESCRIPTION:
                    stateInfo = (StateInfo) intent.getSerializableExtra(IAction.KEY_REQUEST_UI_DESCRIPTION);
                    requestData(stateInfo);
                    break;
//                case IAction.ACTION_SDK_VERSION_NO_MATCH:
//                    new AlertView(getString(R.string.dialog_tip), getString(R.string.apk_version_no_match), null,
//                            new String[]{getString(R.string.operation_ok)}, null, BaseActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
//                        @Override
//                        public void onItemClick(Object o, int i) {
//                            startActivity(new Intent(BaseActivity.this, PersonalSettingActivity.class));
//                        }
//                    }).show();
//                    break;
//                case IAction.ACTION_APK_VERSION_NO_MATCH:
//                    new AlertView(getString(R.string.dialog_tip), getString(R.string.apk_version_no_match), null,
//                            new String[]{getString(R.string.operation_ok)}, null, BaseActivity.this, AlertView.Style.Alert, new OnItemClickListener() {
//                        @Override
//                        public void onItemClick(Object o, int i) {
//                            startActivity(new Intent(BaseActivity.this, PersonalSettingActivity.class));
//                        }
//                    }).show();
//                    break;
                case ACTION_QUIT_APP:
                    exit();
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    public void connectDevice() {
        isReadyToConnect = true;
        Dbug.i(tag, "connectDevice---------, isReadyToConnect===" + isReadyToConnect);
        SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(getApplicationContext());
        String currentSSID = sharedPreferences.getString(CURRENT_SSID, null);
        String currentPWD = sharedPreferences.getString(CURRENT_PWD, null);
        if (TextUtils.isEmpty(currentSSID) || TextUtils.isEmpty(currentPWD)) {
            Dbug.e(tag, "SSID or PWD is null:");
            return;
        }
        mWifiHelper.addNetWorkAndConnect(currentSSID, currentPWD, WifiHelper.WifiCipherType.NONE);
        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
            mNotifyDialog.dismiss();
        }

        if (mNotifyDialog != null) {
            mNotifyDialog.show(getFragmentManager(), "NotifyDialog");
        }
    }


    public void connectDevice(String ssid, String password) {
        /**Check if Wi-Fi enable */
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            NotifyDialog notifyDialog = new NotifyDialog(R.string.dialog_tip, R.string.wifi_is_disable, R.string.exit, new NotifyDialog.OnConfirmClickListener() {
                @Override
                public void onClick() {
                    release();
                }
            });
            notifyDialog.show(getFragmentManager(), "WiFiDisable");
            return;
        }

        isReadyToConnect = true;

        if (TextUtils.isEmpty(ssid)) {
            Dbug.e(tag, "SSID is null");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Dbug.w(tag, "PWD is null");
            password = WifiConfiguration.KeyMgmt.NONE + "";
        }

        if (mNotifyDialog != null) {
            mNotifyDialog.show(getFragmentManager(), "NotifyDialog");
        }

        if (mWifiHelper != null) {
            mConnectingSSID = ssid;
            mPassWord = password;
            if (ARGS_AP_PWD_NONE.equals(password)) {
                Dbug.e(tag, "=======connectDevice=====SSID=" + ssid + ", password=" + WifiHelper.WifiCipherType.NONE);
                mWifiHelper.addNetWorkAndConnect(ssid, password, WifiHelper.WifiCipherType.NONE);
            } else {
                Dbug.e(tag, "=======connectDevice=====SSID=" + ssid + ", password=" + password);
                mWifiHelper.addNetWorkAndConnect(ssid, password, WifiHelper.WifiCipherType.WPA);
            }
        }
    }


    public void disconnectDevice() {
        Dbug.d(tag, "disconnectDevice-----------------");
        ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_DISABLE_DEVICE_WIFI);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                sendCommandToService(IConstant.SERVICE_CMD_CLOSE_SOCKET);

                removeCurrentNetwork();

                mWifiHelper.connectOtherWifi(IConstant.WIFI_PREFIX);
            }
        }, 1000);
    }

    private final static int DELAY = 2000;
    private final static int MSG_ENTER_WORKSPACE = 0X100;

    /**
     * Request UI description text
     */
    private void requestData(final StateInfo stateInfo) {
        ParseHelper parseHelper = ParseHelper.getInstance();
        parseHelper.requestDescriptionText(getApplicationContext(), stateInfo.getParam()[1], new ParseHelper.ResponseListener() {
            @Override
            public void onResponse(boolean isSuccess) {
                if (isSuccess) {
                    Dbug.d(tag, "----------requestData---------:");
                    if (mConnectionErrorNotify != null && mConnectionErrorNotify.isShowing()) {
                        mConnectionErrorNotify.dismiss();
                    }
                    if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                        mNotifyDialog.dismiss();
                    }
                    if (mPasswordErrorDialog != null && mPasswordErrorDialog.isShowing()) {
                        mPasswordErrorDialog.isShowing();
                    }
                    handler.sendEmptyMessage(MSG_ENTER_WORKSPACE);
                    switch (stateInfo.getParam()[0]) {
                        case ARGS_LANG_ZH_CN:
                            setLanguage(Locale.SIMPLIFIED_CHINESE);
                            break;
                        case ARGS_LANG_ZH_TW:
                            setLanguage(Locale.TRADITIONAL_CHINESE);
                            break;
                        case ARGS_LANG_EN_US:
                            setLanguage(Locale.US);
                            break;
                        case ARGS_LANG_DE_DE:
                            setLanguage(Locale.GERMANY);
                            break;
                        case ARGS_LANG_JA_JP:
                            setLanguage(Locale.JAPAN);
                            break;
                        default:
                            break;
                    }
                    sendBroadcast(new Intent(ACTION_DEVICE_LANG_CHANGED));
                } else {
                    if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                        mNotifyDialog.dismiss();
                    }
                    handler.removeMessages(MSG_ENTER_WORKSPACE);
                    if (mAlertView != null && mAlertView.isShowing()) {
                        mAlertView.dismiss();
                    }

                    new AlertView(getString(R.string.dialog_tip), getString(R.string.request_failure),
                            null, new String[]{getString(R.string.exit)},
                            null, BaseActivity2.this, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int i) {
                            release();
                        }
                    }).setCancelable(false).show();
                }
            }
        });
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case MSG_ENTER_WORKSPACE:
                    if (mConnectionErrorNotify != null && mConnectionErrorNotify.isShowing()) {
                        mConnectionErrorNotify.dismiss();
                    }
                    if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
                        mNotifyDialog.dismiss();
                    }
                    boolean isInBackground = AppUtil.isAppInBackground(BaseActivity2.this);
                    Dbug.d(tag, "Wifi is connected >>> isInBackground==" + isInBackground);
                    break;
            }
            return false;
        }
    });

    public void setIsBrowsing(boolean bl) {
        this.isBrowsing = bl;
    }

    public boolean getIsBrowsing() {
        return isBrowsing;
    }

    private void setLanguage(Locale locale) {
        if (locale == null) {
            return;
        }
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getApplicationContext().getResources().updateConfiguration(config, null);
//        Dbug.e(tag, "get current language:" + getResources().getConfiguration().locale.getCountry());
    }

    public NotifyDialog getNotifyDialog() {
        return mNotifyDialog;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucen();
        Dbug.i(tag, ":=========onCreate==============isReadyToConnect=" + isReadyToConnect + ", this=" + this);
        mApplication = (MainApplication) getApplication();
        mWifiHelper = WifiHelper.getInstance(getApplicationContext());
        ActivityStack.getInstance().pushActivity(this);
        mWaiteHandler = new Handler();

        if (mNotifyDialog == null) {
            mNotifyDialog = new NotifyDialog(true, R.string.connecting, R.string.exit, new NotifyDialog.OnConfirmClickListener() {
                @Override
                public void onClick() {
                    //exit();
                    disconnectDevice();
                    mNotifyDialog.dismiss();
                }
            });
        }

        if (mUsbModeDialog == null) {
            mUsbModeDialog = new NotifyDialog(R.string.dialog_tip, R.string.device_in_usb_mode,
                    R.string.exit, new NotifyDialog.OnConfirmClickListener() {
                @Override
                public void onClick() {
                    Dbug.d(tag, "mUsbModeDialog : mUsbModeDialog exit");
                    exit();
                }
            });
        }

        if (mConnectionErrorNotify == null) {
            Dbug.w(tag, "ACTION_DEVICE_CONNECTION_ERROR:new NotifyDialog");
            mConnectionErrorNotify = new NotifyDialog(R.string.dialog_tip, R.string.connect_failed,
                    R.string.confirm, new NotifyDialog.OnConfirmClickListener() {
                @Override
                public void onClick() {
                    if (mConnectionErrorNotify != null && mConnectionErrorNotify.isShowing()) {
                        mConnectionErrorNotify.dismiss();
                    }

                    sendCommandToService(IConstant.SERVICE_CMD_CLOSE_SOCKET);
                    searchDevice();
                }
            });
        }


    }

    public void searchWiFi() {
        /**Check if Wi-Fi enable */
        if (!mWifiHelper.isWifiOpen()) {
            mSearchWiFiDialog = new NotifyDialog(R.string.dialog_tip, R.string.wifi_is_disable, R.string.exit, new NotifyDialog.OnConfirmClickListener() {
                @Override
                public void onClick() {
                    mSearchWiFiDialog.dismiss();
                    mSearchWiFiDialog = null;
                    // exit();
                }
            });
            mSearchWiFiDialog.show(getFragmentManager(), "WiFiDisable");
            return;
        }
        searchDevice();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Dbug.i(tag, "=============onStart==isNeedReconnection=:" + isNeedReconnection + ", this=" + this);
        registerReceiver();
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter(IAction.ACTION_DEVICE_WIFI_DISABLED);
        intentFilter.addAction(IAction.ACTION_SDCARD_STATE);
        intentFilter.addAction(ACTION_DEVICE_CONNECTION_ERROR);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(IAction.ACTION_REJECT_CONNECTION);
        intentFilter.addAction(ACTION_REQUEST_UI_DESCRIPTION);
        intentFilter.addAction(ACTION_QUIT_APP);
//        intentFilter.addAction(IAction.ACTION_SDK_VERSION_NO_MATCH);
//        intentFilter.addAction(IAction.ACTION_APK_VERSION_NO_MATCH);
        getApplicationContext().registerReceiver(mReceiver, intentFilter);
    }

    private void initSocket() {
        Dbug.e(tag, "=============Connect device wifi success, now SERVICE_CMD_INIT_SOCKET");
        sendCommandToService(IConstant.SERVICE_CMD_INIT_SOCKET);
        mApplication.setIsOffLineMode(false);
        mApplication.setIsFirstReadData(true);
        mApplication.setIsNeedReconnect(false);
        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
            mNotifyDialog.dismiss();
        }
        isReadyToConnect = false;
        isNeedReconnection = false;
        onWiFiState(mIsAutoDisabled_Device_WIFI, DEVICE_WIFI_ENABLED);
        connectSuccess();
    }

    public boolean isExistAvailableDevice() {
        boolean flag = false;
        final List<ScanResult> list = mWifiHelper.getSpecifiedSSIDList(WIFI_PREFIX);
        if (list == null)
            return false;
        for (int i = 0; i < list.size(); i++) {
            ScanResult scanResult = list.get(0);
            String selectedSSID = scanResult.SSID;
            SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
            String selectedSSIDPwd = sharedPreferences.getString(selectedSSID, null);
//                    Dbug.d(tag, "selectedSSIDPwd:" + selectedSSIDPwd);
            /**The selected Wi-Fi has connected before*/
            if ((!TextUtils.isEmpty(selectedSSIDPwd)) || (!scanResult.capabilities.contains("WPA"))) {

                flag = true;
            }
        }
        return flag;
    }

    private void searchDevice() {
        final List<ScanResult> list = mWifiHelper.getSpecifiedSSIDList(WIFI_PREFIX);
        if (list != null && list.size() > 1) {
            DeviceListDialog deviceListDialog = new DeviceListDialog();
            deviceListDialog.show(getFragmentManager(), "DeviceListDialog");
            deviceListDialog.setOnItemClickListener(new DeviceListDialog.OnItemClickListener() {
                @Override
                public void onItemClick(boolean isConnected, String ssid, String password) {
                    Dbug.d(tag, "~~~~~~~~~~~searchDevice()~~~~list.size() =>" + list.size() + ", isConnected=" + isConnected);
                    if (isConnected) {
                        initSocket();
                    } else {
                        connectDevice(ssid, password);
                    }
                }
            });
        } else if (list != null && list.size() == 1) {
            ScanResult scanResult = list.get(0);
            String selectedSSID = scanResult.SSID;
            ConnectivityManager cm = (ConnectivityManager) MainApplication.getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            String ssid = wifiManager.getConnectionInfo().getSSID();
            String currentConnectedSSID = null;
            if (!TextUtils.isEmpty(ssid)) {
                currentConnectedSSID = ssid.replace("\"", "");
            }

            Dbug.i(tag, currentConnectedSSID + "==============" + selectedSSID + ", wifi.isConnected()=" + wifi.isConnected());

            /**The selected Wi-Fi is connected*/
            if (!TextUtils.isEmpty(currentConnectedSSID) && currentConnectedSSID.equals(selectedSSID) && wifi.isConnected()) {
                Dbug.d(tag, "Wi-Fi is already connected:" + selectedSSID);
                initSocket();
            } else if ((!scanResult.capabilities.contains("WPA"))) {
                /**No need password*/
                connectDevice(selectedSSID, WifiConfiguration.KeyMgmt.NONE + "");
            } else {
                SharedPreferences sharedPreferences = PreferencesHelper.getSharedPreferences(MainApplication.getApplication());
                String selectedSSIDPwd = sharedPreferences.getString(selectedSSID, null);
//                    Dbug.d(tag, "selectedSSIDPwd:" + selectedSSIDPwd);
                /**The selected Wi-Fi has connected before*/
                if (!TextUtils.isEmpty(selectedSSIDPwd)) {
                    connectDevice(selectedSSID, selectedSSIDPwd);
                    Dbug.w(tag, "currentSSID and currentPWD not empty.");
                } else {
                    InputPasswordDialog inputPasswordDialog = InputPasswordDialog.newInstance(selectedSSID);
                    inputPasswordDialog.show(getFragmentManager(), "inputPasswordDialog");
                    inputPasswordDialog.setOnInputCompletionListener(new InputPasswordDialog.OnInputCompletionListener() {
                        @Override
                        public void onCompletion(String ssid, String password) {
                            Dbug.w(tag, "onCompletion. ssid=" + ssid);
                            connectDevice(ssid, password);
                        }
                    });
                }
            }
        } else {
            Dbug.e(tag, "No " + WIFI_PREFIX);
            showToastInfo("对不起，不存在理赔保记录仪WiFi！");
        }
    }

    private void showToastInfo(String info) {
        Toast.makeText(this.getApplicationContext(), info, Toast.LENGTH_LONG).show();
    }

    private void exit() {
        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
            mNotifyDialog.dismiss();
        }
        Dbug.d(tag, "onItemClick:System.exit(0)");
        stopService(new Intent(BaseActivity2.this, CommunicationService.class));
        ActivityStack.getInstance().clearAllActivity();
    }

    public void showToast(String info) {
        if (mToastShort != null) {
            mToastShort.setText(info);
        } else {
            mToastShort = Toast.makeText(this, info, Toast.LENGTH_SHORT);
        }
        mToastShort.show();
    }

    public void showToast(int info) {
        showToast(getResources().getString(info));
    }

    public void showToastLong(String msg) {
        if (mToastLong != null) {
            mToastLong.setText(msg);
        } else {
            mToastLong = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        }
        mToastLong.show();
    }

    public void showToastLong(int msg) {
        showToastLong(getResources().getString(msg));
    }

    public void changeFragment(int containerId, Fragment fragment) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(containerId, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void onItemClick(Object o, int i) {
        Dbug.w(tag, "onItem click: " + i);
        if (mAlertView != null) {
            mAlertView.dismiss();
            release();
            mApplication.setErrorFlag(false);
        } else {
            Dbug.d(tag, "onItem click: " + i);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();

        isNeedReconnection = AppUtil.isAppInBackground(this);
        Dbug.i(tag, "=============onStop==isNeedReconnection=:" + isNeedReconnection + ", this=" + this);


        getApplicationContext().unregisterReceiver(mReceiver);
    }

    protected void removeCurrentNetwork() {
        Dbug.i(tag, "==========removeCurrentNetwork");

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null || wifiInfo.getSSID() == null) {
            Dbug.e(tag, "-=-=-=wifiInfo is null or  wifiInfo.getSSID() is null");
            return;
        }
        if (wifiInfo.getSSID().contains(WIFI_PREFIX_CAMERA)||wifiInfo.getSSID().contains(WIFI_PREFIX_CARDVR)||wifiInfo.getSSID().contains(WIFI_PREFIX_168)) {
            Dbug.w(tag, "wifiInfo.getNetworkId:" + wifiInfo.getNetworkId());
//            wifiManager.disableNetwork(wifiInfo.getNetworkId());
//            wifiManager.disconnect();
//            wifiManager.removeNetwork(wifiInfo.getNetworkId());
//            wifiManager.saveConfiguration();
            mWifiHelper.remoteNetWork(wifiInfo.getNetworkId());
        }
    }

    public void sendCommandToService(int cmd) {
        Intent intent = new Intent(this, CommunicationService.class);
        intent.putExtra(IConstant.SERVICE_CMD, cmd);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        if (mAlertView != null) {
            mAlertView.dismiss();
        }
        super.onDestroy();
    }

    public static void delete(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    public void release() {
        Dbug.w(tag, "APP release...isNeedReconnection=" + isNeedReconnection);

        if (mNotifyDialog != null && mNotifyDialog.isShowing()) {
            mNotifyDialog.dismiss();
        }
        ControlManager.getInstance().sendCommand(ICommon.CTP_ID_DEFAULT, ICommon.CMD_DISABLE_DEVICE_WIFI, ARGS_DISABLE_DEVICE_WIFI);

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                /**Disconnect device Wi-Fi*/
                removeCurrentNetwork();
                mWifiHelper.connectOtherWifi(IConstant.WIFI_PREFIX);

                /**Remove current SSID & PWD from SharedPreferences*/
                PreferencesHelper.remove(MainApplication.getApplication(), CURRENT_SSID);
                PreferencesHelper.remove(MainApplication.getApplication(), CURRENT_PWD);

                /**Remove device version info from SharedPreferences*/
                PreferencesHelper.remove(MainApplication.getApplication(), DEVICE_VERSION_INFO);

                stopService(new Intent(MainApplication.getApplication(), CommunicationService.class));
                ActivityStack.getInstance().clearAllActivity();
                //StreamPlayer.getInstance().releasePlayer();
                mApplication.setIsOffLineMode(true);
                mApplication.setRealCamera(false);
                if (mApplication.getDeviceUUID() == null) {
                    Dbug.e(tag, "Device UUID is null");
                    return;
                }
                String thumPath = Environment.getExternalStorageDirectory().getPath() + "/" + mApplication.getAppName() + "/" + mApplication.getDeviceUUID() + "/thumb/";
                File thumbFile = new File(thumPath);
                if (thumbFile.exists()) {
                    AppUtil.deleteFile(thumbFile);
                }
                Dbug.e(tag, "Exit app");
            }
        }, 1000L);
    }

    public void onMountState(String mountState, final String msg) {
        Dbug.e(tag, "mountState:" + mountState);
        switch (mountState) {
            case ARGS_SDCARD_OFFLINE:
                //showToastLong(getString(R.string.sdcard_offline));
                mApplication.setSdcardState(false);
                break;
            case ARGS_SDCARD_ONLINE:
                //showToastLong(getString(R.string.sdcard_online));
                mApplication.setSdcardState(true);
                break;
            default:
                showToastLong(msg);
                break;
        }
    }

    @Override
    public void onCancel() {
        if (mUsbModeDialog != null && mUsbModeDialog.isShowing()) {
            mUsbModeDialog.dismiss();
        }
    }

    @Override
    public void onShow() {
        if (mUsbModeDialog != null && mUsbModeDialog.isShowing()) {
            mUsbModeDialog.dismiss();
        }
        if (mUsbModeDialog != null) {
            mUsbModeDialog.show(getFragmentManager(), "mUsbModeDialog");
        }
    }

    public void displayVideo() {
        int ss = 0;
    }

    public void onWiFiState(boolean isAutoDisable, int state) {

    }

    /**
     * 设置通知栏透明化，和自定义标题栏颜色保持一致
     */
    protected void setTranslucen() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            if(mSystemBarTintManager == null)
                mSystemBarTintManager = new SystemBarTintManager(this);
            mSystemBarTintManager.setStatusBarTintEnabled(true);
            mSystemBarTintManager.setStatusBarTintResource(R.color.default_title_color);//通知栏所需颜色
            //tintManager.setStatusBarTintEnabled(false);
        }
    }

    /**
     * 设置通知栏透明化，和自定义标题栏颜色保持一致
     */
    protected void setTranslucen(int resId_color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            if(mSystemBarTintManager == null)
                mSystemBarTintManager = new SystemBarTintManager(this);
            mSystemBarTintManager.setStatusBarTintEnabled(false);
            mSystemBarTintManager.setStatusBarTintResource(resId_color);//通知栏所需颜色
            //tintManager.setStatusBarTintEnabled(false);
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }


    protected void checkNetTimeOut() {
        if (timeOutRunable != null)
            mWaiteHandler.removeCallbacks(timeOutRunable);
        mWaiteHandler.postDelayed(timeOutRunable, 30000);
    }

    /**
     * 等待进度窗体显示
     */
    protected void showProcessDialog() {
        try {
            hideProgressDialog();
            mProgressDialog = null;
            if (mProgressDialog == null) {
                mProgressDialog = new WaitDialog(this);
            }
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);
            if (!isFinishing()) {
                mProgressDialog.show();
            }
        } catch (Exception e) {
        }
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 等待进度窗体影藏或销毁
     */
    protected void hideProgressDialog() {
        removeTimeOut();
        try {
            if (!isFinishing() && mProgressDialog != null
                    && mProgressDialog.isShowing()) {
                mProgressDialog.hide();
            }
        } catch (Exception e) {
        }
    }

    protected void removeTimeOut() {
        if (timeOutRunable != null)
            mWaiteHandler.removeCallbacks(timeOutRunable);
    }

    Runnable timeOutRunable = new Runnable() {
        @Override
        public void run() {
            if (!isDeal) {
                isTimeOut = true;
                hideProgressDialog();
                showTimeOutError();
            }
        }
    };

    protected void resetTimeOutStatus() {
        isTimeOut = false;
        isDeal = false;
    }

    protected void connectSuccess() {
        Toast toast = null;
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_connect_sucess,
                null);
        toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.TOP, 0, 250);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    protected void connectError() {
        Toast toast = null;
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.dialog_connect_cancle,
                null);
        toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.TOP, 0, 250);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();
    }

    protected void showTimeOutError() {
        showLongThoast("超时！");
    }

    protected void showLongThoast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void refresh(Object... param) {
        int flag = ((Integer) param[0]).intValue();// 获取第一个参�?
        switch (flag) {
            case BaseActivity2.ERROR:
//			Toast.makeText(this, "网络中断,请稍后操作！", 3000).show();
                break;
            case BaseActivity2.COOKIE_INVILD:
                Toast.makeText(this, "登陆过期!!", Toast.LENGTH_SHORT).show();
                break;
        }
    }
    @Override
    public void onDownloadSoft(boolean is_sucess,String path_name,String file_name)
    {

    }
}
